package com.wanglianyun.aspect;

import com.wanglianyun.config.datasource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * Description:
 * Copyright: Copyright (c) 2024
 * Create Time: 2024-11-13 16:36
 *
 * @author wanglianyun
 */
@Component
@Aspect
@Slf4j
public class DynamicDataSourceAspect {
    private static final String DEFAULT_DATASOURCE = "studentDataSource";

    @Pointcut("@annotation(com.wanglianyun.aspect.DS)")
    public void dsPointCut() {}

    @Before("dsPointCut() && @annotation(ds)")
    public void changeDataSource(JoinPoint joinPoint, DS ds) {
        String dataSourceName = ds.value();
        if (DynamicDataSourceContextHolder.containsDataSource(dataSourceName)) {
            // 切换数据源
            DynamicDataSourceContextHolder.setDataSource(dataSourceName);
            System.out.println("切换到数据源：" + dataSourceName);
            log.info("切换到数据源：{}", dataSourceName);
        } else {
            //可以设置默认的数据源
            log.error("数据源不存在：{}", dataSourceName);
        }
    }

    @After("@annotation(ds)")
    public void clearDataSource(JoinPoint joinPoint, DS ds) {
        // 使用结束后清除当前的数据源防止内存泄露
        DynamicDataSourceContextHolder.clear();
    }
}

